package com.szh.consumer.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 错误消息 处理队列
 * MQ,重试达到上限的消息，入专门处理的队列
 */
@Configuration
public class ErrorMessageConfig {

    public static final String ERROR_EXCHANGE_NAME="error.direct";
    public static final String ERROR_QUEUE_NAME="error.queue";
    public static final String ERROR_MESSAGE_ROUTE_KEY="error";

    @Bean
    public DirectExchange errorMessageExchange(){
        return new DirectExchange(ERROR_EXCHANGE_NAME);
    }
    @Bean
    public Queue errorQueue(){
        return new Queue(ERROR_QUEUE_NAME);
    }
    @Bean
    public Binding errorMessageBinding(){
        return BindingBuilder.bind(errorQueue()).to(errorMessageExchange()).with(ERROR_MESSAGE_ROUTE_KEY);
    }

    /**重写默认的消息失败处理方式（默认是达到重试上限，拒绝消息）
     * @param rabbitTemplate
     * @return MessageRecoverer 默认有三种。看这个接口的子类
     */
    @Bean
    public MessageRecoverer republishMessageRecoverer(RabbitTemplate rabbitTemplate){
        return new RepublishMessageRecoverer(rabbitTemplate, ERROR_EXCHANGE_NAME, ERROR_MESSAGE_ROUTE_KEY);
    }

}
